package com.campus.common.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.campus.api.util.JwtHelper;
import com.campus.api.util.UserContext;
import com.campus.common.enumUtil.ResultCodeEnum;
import com.campus.common.repairTechnician.entity.RepairTechnician;
import com.campus.common.repairTechnician.entity.vo.RepairTechnicianVO;
import com.campus.common.repairTechnician.mapper.RepairTechnicianMapper;
import com.campus.common.result.Result;
import com.campus.common.student.job.entity.Student;
import com.campus.common.student.job.vo.StudentVO;
import com.campus.common.student.mapper.StudentMapper;
import com.campus.common.teacher.job.entity.Teacher;
import com.campus.common.teacher.job.vo.TeacherVO;
import com.campus.common.teacher.mapper.TeacherMapper;
import com.campus.common.user.entity.dto.*;
import com.campus.common.user.entity.pojo.User;
import com.campus.common.user.entity.vo.LoginVO;
import com.campus.common.user.entity.vo.UserListVO;
import com.campus.common.user.entity.vo.UserVO;
import com.campus.common.user.mapper.AuthMapper;
import com.campus.common.user.service.AuthService;
import com.campus.common.userRole.service.UserRoleService;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

@Service
public class AuthServiceImpl extends ServiceImpl<AuthMapper, User> implements AuthService {


    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private TeacherMapper teacherMapper;

    @Autowired
    private RepairTechnicianMapper repairTechnicianMapper;

    @Autowired
    private AuthMapper authMapper;

    @Override
    public Result userLogin(LoginDTO loginDTO) {

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, loginDTO.getUsername());
        User user = authMapper.selectOne(queryWrapper);
        if (user == null) {
            return Result.build(null, ResultCodeEnum.USER_ERROR);
        } else if (!Objects.equals(user.getPassword(), loginDTO.getPassword())) {
            return Result.build(null, ResultCodeEnum.PASSWORD_ERROR);
        }
//        Duration tokenTTL = Duration.ofMinutes(10);

//        String token=jwtTool.createToken(user.getId().toString(), tokenTTL);
        String token = JwtHelper.createToken(user.getId());

        LoginVO loginVO = new LoginVO();
        loginVO.setToken(token);
        //判断是否为首次登陆
        if (user.getPassword().isEmpty()) {
            user.setPassword("");
            user.setRegisterDate(null);
            loginVO.setUser(user);
            return Result.build(loginVO, 208, null);
        }
        user.setPassword("");
        user.setRegisterDate(null);
        loginVO.setUser(user);

        return Result.build(loginVO);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result userRegister(RegisterDTO registerDTO) {

        if (!Objects.equals(registerDTO.getPassword(), registerDTO.getRePassword())) {
            return Result.build(ResultCodeEnum.PASSWORD_MISMATCH);
        }

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, registerDTO.getUsername());
        User user = baseMapper.selectOne(queryWrapper);
        if (user != null) {
            return Result.build(ResultCodeEnum.USERNAME_USED);
        }
        User user1 = new User();
        BeanUtils.copyProperties(registerDTO, user1);
        user1.setRegisterDate(LocalDateTime.now());
        baseMapper.insert(user1);

        LambdaQueryWrapper<User> queryWrapperTwo = new LambdaQueryWrapper<>();
        queryWrapperTwo.eq(User::getUsername, user1.getUsername());
        User userTwo = baseMapper.selectOne(queryWrapperTwo);

        return Result.build(userTwo, ResultCodeEnum.SUCCESS);
    }

    @Override
    public Result editUser(EditUserDTO editUserDTO) {
        int userId = UserContext.getUserId();
        User user = baseMapper.selectById(userId);
        if (Optional.ofNullable(user).isEmpty()) {
            throw new RuntimeException("未查询到该用户信息");
        }

        if (editUserDTO.getPassword() != null && editUserDTO.getPassword() != "") {
            if (editUserDTO.getPassword().equals(user.getPassword())) {
                user.setPassword(editUserDTO.getNewPassword());
                baseMapper.updateById(user);
                return Result.success("修改密码成功");
            } else {
                return Result.fail("密码输入错误");
            }

        }
        String password = user.getPassword();

        BeanUtils.copyProperties(editUserDTO, user);
        user.setPassword(password);
        int i = baseMapper.updateById(user);
        if (i < 1) {
            throw new RuntimeException("修改用户信息失败");
        }
        return Result.success();

    }

    @Override
    public Result lookOwn() {
        int userId = UserContext.getUserId();
        User user = authMapper.selectById(userId);
        if (Optional.ofNullable(user).isEmpty()) {
            throw new RuntimeException("未查询到该用户信息");
        }

        switch (user.getIdentity()) {
            case 0:
                return getStudentInfo(user);
            case 1:
                return getTeacherInfo(user);
            case 2:
                return getAdminInfo(user);
            case 3:
                return getRepairTechnicianInfo(user);
            default:
                return Result.fail("返回信息失败");
        }
    }

    private Result getAdminInfo(User user) {
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        return Result.success(userVO);

    }

    @Override
    public Result getAllUserInfo(LookUserDTO lookUserDTO) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();

        Optional.ofNullable(lookUserDTO.getIdentity()).filter(s -> !s.trim().isEmpty())
                .ifPresent(identity -> queryWrapper.eq(User::getIdentity, Integer.valueOf(identity)));

        Optional.ofNullable(lookUserDTO.getSex()).filter(sex -> !sex.trim().isEmpty())
                .ifPresent(sex -> queryWrapper.eq(User::getSex, sex));

        Optional.ofNullable(lookUserDTO.getName()).filter(name -> !name.trim().isEmpty())
                .ifPresent(name -> queryWrapper.like(User::getName, name));

        List<User> users = authMapper.selectList(queryWrapper);

        List<UserListVO> listUser = new ArrayList<>();
        if (users.size() > 0) {
            users.stream().forEach(user -> {
                UserListVO userListVO = new UserListVO();
                // 根据身份设置用户类型
                switch (user.getIdentity()) {
                    case 0:
                        userListVO.setUserType("学生");
                        break;
                    case 1:
                        userListVO.setUserType("教师");
                        break;
                    case 2:
                        userListVO.setUserType("管理员");
                        break;
                    case 3:
                        userListVO.setUserType("维修人员");
                        break;
                    default:
                        return;
                }
                BeanUtils.copyProperties(user, userListVO);
                listUser.add(userListVO);
            });
        }

        return Result.success(listUser);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result removeByUserId(Integer id) {

        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId, id);

        User user = authMapper.selectOne(queryWrapper);
        if (Optional.ofNullable(user).isEmpty()) {
            return Result.fail("未查询到该用户信息");
        } else {
            switch (user.getIdentity()) {
                case 0:
                    deleteStudent(user.getId());
                    int delete = authMapper.delete(queryWrapper);
                    if(delete>0){
                        return Result.success("删除学生信息成功");
                    }else{
                        return Result.success("删除学生信息失败");
                    }
                case 1:
                    deleteTeacher(user.getId());
                    int delete1 = authMapper.delete(queryWrapper);
                    if(delete1>0){
                        return Result.success("删除教师信息成功");
                    }else{
                        return Result.success("删除教师信息失败");
                    }
                case 2:
                    int delete2 = authMapper.delete(queryWrapper);
                    if(delete2>0){
                        return Result.success("删除管理员信息成功");
                    }else{
                        return Result.success("删除管理员信息失败");
                    }
                default:
                    return Result.fail("返回信息失败");
            }

        }

    }


    private void deleteTeacher(Integer id) {
        int i = teacherMapper.delete(new LambdaQueryWrapper<Teacher>().eq(Teacher::getUserId, id));
        if (i > 0) {
            return;
        } else {
            throw new RuntimeException("删除教师信息失败");
        }
    }

    private void deleteStudent(Integer userId) {
        int i = studentMapper.delete(new LambdaQueryWrapper<Student>().eq(Student::getUserId, userId));
        if (i > 0) {
            return;
        } else {
            throw new RuntimeException("删除学生信息失败");
        }
    }

    @Override
    public Result changePassword(LoginDTO loginDTO) {
        if (loginDTO.getPassword().isEmpty()) {
            return Result.fail("输入的密码不能为空!");
        } else {
            User user = authMapper.selectOne(
                    new LambdaQueryWrapper<User>().eq(User::getUsername, loginDTO.getUsername())
            );
            user.setPassword(loginDTO.getPassword());
            authMapper.updateById(user);
            return Result.success("修改密码成功!");
        }
    }

    @Override
    public Result insertAdmin(InsertUserDTO insertUserDTO) {
        User user = new User();
        String workId = UUID.randomUUID().toString();
        user.setIdentity(2);
        user.setWorkId(workId);
        user.setUsername(insertUserDTO.getUsername());
        user.setPassword(insertUserDTO.getPassword());
        user.setName(insertUserDTO.getName());
        user.setSex(insertUserDTO.getSex());
        user.setRegisterDate(LocalDateTime.now());

//        user.setAge(insertUserDTO.getAge());
        int insert = baseMapper.insert(user);
        if (insert > 0) {
            return Result.success(insertUserDTO);
        } else {
            return Result.fail("插入管理员信息失败");
        }

    }


    public Result getStudentInfo(User user) {
        LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Student::getUserId, user.getId());
        Student student = studentMapper.selectOne(queryWrapper);
        if (Optional.ofNullable(student).isEmpty()) {
            throw new RuntimeException("未查询到该用户信息");
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        userVO.setMajor(student.getMajor());
        userVO.setCollege(student.getCollege());
        userVO.setEnrollmentYear(student.getEnrollmentYear());
        userVO.setStuClass(student.getStuClass());
        return Result.success(userVO);
    }

    public Result getTeacherInfo(User user) {
        LambdaQueryWrapper<Teacher> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teacher::getUserId, user.getId());
        Teacher teacher = teacherMapper.selectOne(queryWrapper);
        if (Optional.ofNullable(teacher).isEmpty()) {
            throw new RuntimeException("未查询到该教师信息");
        }
//        TeacherVO teacherVO = new TeacherVO();
//        BeanUtils.copyProperties(user, teacherVO);
//        BeanUtils.copyProperties(teacher, teacherVO);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user, userVO);
        userVO.setOffice(teacher.getOffice());
        return Result.success(userVO);
    }

    public Result getRepairTechnicianInfo(User user) {
        RepairTechnician repairTechnician = repairTechnicianMapper.selectById(user.getId());
        if (Optional.ofNullable(repairTechnician).isEmpty()) {
            throw new RuntimeException("未查询到该用户信息");
        }
        RepairTechnicianVO repairTechnicianVO = new RepairTechnicianVO();
        BeanUtils.copyProperties(user, repairTechnicianVO);
        BeanUtils.copyProperties(repairTechnician, repairTechnicianVO);
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(repairTechnicianVO, userVO);

        return Result.success(userVO);
    }


}
